package com.it.ssh.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.it.ssh.dao.BookUserDao;
import com.it.ssh.entity.BookUser;


public class BookUserDaoImpl implements BookUserDao {
	private SessionFactory sessionFactory;
	

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public boolean login(BookUser user) {
		String hql="from BookUser where id=? and password=?";
		Session session=sessionFactory.openSession();
		Query q=session.createQuery(hql);
		q.setInteger(0, user.getId());
		q.setString(1, user.getPassword());
		Object obj=q.uniqueResult();
		boolean flag=false;
		if(obj!=null){
			flag=true;
		}
		session.close();
		return flag;
	}

	@Override
	public boolean add(BookUser user) {
		Session session = sessionFactory.openSession();
		Transaction tran=session.beginTransaction();
		session.save(user);
		tran.commit();
		return true;
	}

	@Override
	public boolean update(BookUser user) {
		Session session = sessionFactory.openSession();
		Transaction tran=session.beginTransaction();
		session.update(user);
		tran.commit();
		return true;
	}

	@Override
	public boolean delete(int id) {
		Session session = sessionFactory.openSession();
		Transaction tran=session.beginTransaction();
		BookUser user = new BookUser();
		user.setId(id);
		session.delete(user);
		tran.commit();
		return true;
	}

	@Override
	public BookUser queryById(int id) {
		String hql = "from BookUser where id =?";
		Session session=sessionFactory.openSession();
		Query q=session.createQuery(hql);
		q.setInteger(0,id);
		BookUser user = new BookUser();
		if(q.uniqueResult()!=null){
			user=(BookUser) q.uniqueResult();
		}
		session.close();
		return user;
	}

	@Override
	public List<BookUser> queryAll() {
		String hql="from BookUser";
		Session session=sessionFactory.openSession();
		Query q=session.createQuery(hql);
		List<BookUser> list=q.list();
		session.close();
		return list;
	}

}
